#ifndef __PARSER_CPP__
#define __PARSER_CPP__

#include "config.h"
#include "parser.h"

Parser::Parser(char *infile, int this_src){
  ifile=fopen(infile, "r");
  nxt_cmd.src=this_src;
  nxt_cmd.delay = L1_LATENCY;
  total = 0;
  /* Grab the first command */
  ReadNextCmd();
}

Parser::~Parser(){
  fclose(ifile);
}

void Parser::Update() {
  if (QEmpty())
    return;
  //cout<<"next cmd: "<<clk_next_req<<endl;
  if(cur_cyc==clk_next_req){
again:
    /* Issue new command */
    memQ->NewReq(nxt_cmd);
    /* Grab next command */
    if(QEmpty())
      return;
    ReadNextCmd();
    if(cur_cyc==clk_next_req && !QEmpty())
      goto again;
  }
  return;
}

void Parser::ReadNextCmd(){
  /* Grab next command */
  char line[128];
  char cmd_type[20];
  unsigned long addr = 0;
  unsigned long mul = 1;
  void* rc;
  rc = fgets(line,sizeof(line),ifile);
  if (rc == NULL)
    return;
  //assert(rc != NULL);
  sscanf(line, "0x%lX %ld %s", &addr, &clk_next_req, cmd_type);

  total++;
  nxt_cmd.addr = addr;

  /* DEBUG */
  //cout<<"addr: "<<nxt_cmd.addr<<" clk_next: "<<clk_next_req<<" cmd: "<<cmd_type[0]<<endl;

  if (cmd_type[0]=='L') nxt_cmd.cmd=R;
  else nxt_cmd.cmd=W;
}

#endif
